<template>
  <common-layout title="供应商管理">
    <template #header-buttons >
      <div class="card-header">
        <el-button type="primary" @click="handleCreate">新增供应商</el-button>
      </div>
    </template>

    <template #search-form>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="供应商编码" style="width: 260px;">
          <el-input v-model="searchForm.supplierCode" placeholder="请输入供应商编码"></el-input>
        </el-form-item>
        <el-form-item label="供应商名称" style="width: 260px;">
          <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人" style="width: 260px;">
          <el-input v-model="searchForm.contactPerson" placeholder="请输入联系人"></el-input>
        </el-form-item>
        <el-form-item label="状态" style="width: 260px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <template #data-content>
      <!-- 供应商列表 -->
      <el-table :data="pureSupplierList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="supplierCode" label="供应商编码"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
        <el-table-column prop="supplierShortName" label="供应商简称"></el-table-column>
        <el-table-column prop="contactPerson" label="联系人"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="supplierLevel" label="等级"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </template>
  </common-layout>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="供应商详情" width="70%">
      <el-descriptions :column="2" title="基本信息" border>
        <el-descriptions-item label="供应商编码">{{ currentSupplier?.supplierCode }}</el-descriptions-item>
        <el-descriptions-item label="供应商名称">{{ currentSupplier?.supplierName }}</el-descriptions-item>
        <el-descriptions-item label="供应商简称">{{ currentSupplier?.supplierShortName }}</el-descriptions-item>
        <el-descriptions-item label="供应商类型">{{ currentSupplier?.supplierType }}</el-descriptions-item>
        <el-descriptions-item label="供应商等级">{{ currentSupplier?.supplierLevel }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ currentSupplier?.status === 1 ? '启用' : '禁用' }}</el-descriptions-item>
        <el-descriptions-item label="业务联系人">{{ currentSupplier?.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentSupplier?.contactPhone }}</el-descriptions-item>
        <!-- 电子邮箱字段已移除 -->
        <el-descriptions-item label="财务联系人">{{ currentSupplier?.financialContactPerson }}</el-descriptions-item>
        <el-descriptions-item label="财务电话">{{ currentSupplier?.financialContactPhone }}</el-descriptions-item>
        <el-descriptions-item label="财务邮箱">{{ currentSupplier?.financialEmail }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ currentSupplier?.address }}</el-descriptions-item>
        <el-descriptions-item label="纳税人识别号">{{ currentSupplier?.taxpayerId }}</el-descriptions-item>
        <el-descriptions-item label="开户行及账号">{{ currentSupplier?.bankAccount }}</el-descriptions-item>
        <el-descriptions-item label="发票类型">{{ currentSupplier?.invoiceType }}</el-descriptions-item>
        <el-descriptions-item label="开票地址">{{ currentSupplier?.invoiceAddress }}</el-descriptions-item>
        <el-descriptions-item label="开票电话">{{ currentSupplier?.invoicePhone }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentSupplier?.remark }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑供应商' : '创建供应商'"
      width="70%"
    >
      <el-form
        :model="supplierForm"
        ref="supplierFormRef"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="供应商编码" v-if="isEdit">
          <el-input v-model="supplierForm.supplierCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="supplierForm.supplierName"></el-input>
        </el-form-item>
        <el-form-item label="供应商简称" prop="supplierShortName">
          <el-input v-model="supplierForm.supplierShortName"></el-input>
        </el-form-item>
        <el-form-item label="供应商类型" prop="supplierType">
          <el-input v-model="supplierForm.supplierType"></el-input>
        </el-form-item>
        <el-form-item label="供应商等级" prop="supplierLevel">
          <el-select v-model="supplierForm.supplierLevel">
            <el-option label="优质供应商" value="优质供应商"></el-option>
            <el-option label="普通供应商" value="普通供应商"></el-option>
            <el-option label="潜在供应商" value="潜在供应商"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人类型" prop="contactType">
          <el-select v-model="supplierForm.contactType">
            <el-option label="业务联系人" value="业务"></el-option>
            <el-option label="财务联系人" value="财务"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactPerson">
          <el-input v-model="supplierForm.contactPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="supplierForm.contactPhone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="supplierForm.email" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        <!-- 财务联系人相关字段已移除，统一通过联系人类型选择处理 -->
        <el-form-item label="地址" prop="address">
          <el-input v-model="supplierForm.address"></el-input>
        </el-form-item>
        <el-form-item label="纳税人识别号" prop="taxpayerId">
          <el-input v-model="supplierForm.taxpayerId"></el-input>
        </el-form-item>
        <el-form-item label="开户行及账号" prop="bankAccount">
          <el-input v-model="supplierForm.bankAccount"></el-input>
        </el-form-item>
        <el-form-item label="发票类型" prop="invoiceType">
          <el-select v-model="supplierForm.invoiceType">
            <el-option label="增值税专用发票" value="增值税专用发票"></el-option>
            <el-option label="增值税普通发票" value="增值税普通发票"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开票地址" prop="invoiceAddress">
          <el-input v-model="supplierForm.invoiceAddress"></el-input>
        </el-form-item>
        <el-form-item label="开票电话" prop="invoicePhone">
          <el-input v-model="supplierForm.invoicePhone"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="supplierForm.remark" type="textarea"></el-input>
        </el-form-item>
        <el-form-item v-if="!isEdit">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="formDialogVisible = false">取消</el-button>
        </el-form-item>
        <el-form-item v-if="isEdit">
          <el-button type="primary" @click="handleUpdate">更新</el-button>
          <el-button @click="formDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="400px">
      <p>确定要删除供应商 <span style="color: #f56c6c">{{ currentSupplier?.supplierName }}</span> 吗？</p>
      <p style="color: #f56c6c; font-size: 12px;">删除后将无法恢复，且会检查是否有未完成的采购订单或未结算的应付账款。</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </template>
    </el-dialog>

</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getSuppliers, getSupplier, createSupplier, updateSupplier, deleteSupplier, updateSupplierStatus } from '@/api/supplier';
import CommonLayout from '../components/CommonLayout.vue';

// 状态管理
const supplierList = ref([]);
// 直接使用supplierList，移除多余的计算属性
const pureSupplierList = computed(() => supplierList.value || []);

// 移除不再需要的ensurePureArray方法
const currentSupplier = ref(null);
const detailDialogVisible = ref(false);
const formDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const isEdit = ref(false);

// 搜索表单
const searchForm = reactive({
  supplierCode: '',
  supplierName: '',
  contactPerson: '',
  status: ''
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 供应商表单
const supplierForm = reactive({
  id: 0,
  supplierCode: '',
  supplierName: '',
  supplierShortName: '',
  supplierType: '',
  supplierLevel: '普通供应商',
  contactType: '业务', // 默认业务联系人
  contactPerson: '',
  contactPhone: '',
  email: '',
  address: '',
  taxpayerId: '',
  bankAccount: '',
  invoiceType: '增值税专用发票',
  invoiceAddress: '',
  invoicePhone: '',
  remark: '',
  status: 1
});

// 表单验证规则
const formRules = {
  supplierName: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' }
  ],
  supplierShortName: [
    { required: true, message: '请输入供应商简称', trigger: 'blur' }
  ],
  contactType: [
    { required: true, message: '请选择联系人类型', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  taxpayerId: [
    { required: true, message: '请输入纳税人识别号', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入开户行及账号', trigger: 'blur' }
  ],
  invoiceType: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  invoiceAddress: [
    { required: true, message: '请输入开票地址', trigger: 'blur' }
  ],
  invoicePhone: [
    { required: true, message: '请输入开票电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  financialContactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的财务联系电话', trigger: 'blur' }
  ],
  financialEmail: [
    { type: 'email', message: '请输入正确的财务邮箱格式', trigger: 'blur' }
  ]
};

// 加载供应商列表
const loadSuppliers = async () => {
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    };
    
    const response = await getSuppliers(params);
    
    // 简化数据处理逻辑
    let items = [];
    if (response && typeof response === 'object') {
      if ('items' in response) {
        if (Array.isArray(response.items)) {
          items = response.items;
        } else if (typeof response.items === 'object' && '$values' in response.items && Array.isArray(response.items.$values)) {
          // 处理特殊格式：items对象包含$values数组
          items = response.items.$values;
        }
      } else if (Array.isArray(response)) {
        items = response;
      }
    }

    // 转换字段大小写并移除$id属性
    items = items.map(item => {
      const newItem = {};
      // 转换属性名：大写开头转为小写开头
      Object.keys(item).forEach(key => {
        if (key === '$id') return; // 跳过$id属性
        // 首字母小写，其余保持不变
        const newKey = key.charAt(0).toLowerCase() + key.slice(1);
        newItem[newKey] = item[key];
      });
      // 处理嵌套对象
      if (newItem.contacts && Array.isArray(newItem.contacts)) {
        newItem.contacts = newItem.contacts.map(contact => {
          const newContact = {};
          Object.keys(contact).forEach(key => {
            if (key === '$id') return;
            const newKey = key.charAt(0).toLowerCase() + key.slice(1);
            newContact[newKey] = contact[key];
          });
          return newContact;
        });
      } else if (newItem.contacts && typeof newItem.contacts === 'object' && '$values' in newItem.contacts) {
        newItem.contacts = newItem.contacts.$values.map(contact => {
          const newContact = {};
          Object.keys(contact).forEach(key => {
            if (key === '$id') return;
            const newKey = key.charAt(0).toLowerCase() + key.slice(1);
            newContact[newKey] = contact[key];
          });
          return newContact;
        });
      }
      return newItem;
    });

    supplierList.value = items;
    pagination.total = response?.total || 0;
  } catch (error) {
    ElMessage.error('获取供应商列表失败');
    console.error('Failed to load suppliers:', error);
    // 确保出错时supplierList也是数组
    supplierList.value = [];
    pagination.total = 0;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  loadSuppliers();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  pagination.currentPage = 1;
  loadSuppliers();
};

// 分页大小变更
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadSuppliers();
};

// 分页当前页变更
const handleCurrentChange = (current) => {
  pagination.currentPage = current;
  loadSuppliers();
};

// 查看详情
const handleView = async (row) => {
  try {
    currentSupplier.value = { ...row };
    const response = await getSupplier(row.supplierCode);
    let data = response;
    if (data) {
      // 转换数据格式
      const formattedData = {};
      Object.keys(data).forEach(key => {
        if (key === '$id') return;
        const newKey = key.charAt(0).toLowerCase() + key.slice(1);
        formattedData[newKey] = data[key];
      });
      // 处理联系人数据
      if (formattedData.contacts && Array.isArray(formattedData.contacts)) {
        formattedData.contacts = formattedData.contacts.map(contact => {
          const newContact = {};
          Object.keys(contact).forEach(key => {
            if (key === '$id') return;
            const newKey = key.charAt(0).toLowerCase() + key.slice(1);
            newContact[newKey] = contact[key];
          });
          return newContact;
        });
      } else if (formattedData.contacts && typeof formattedData.contacts === 'object' && '$values' in formattedData.contacts) {
        formattedData.contacts = formattedData.contacts.$values.map(contact => {
          const newContact = {};
          Object.keys(contact).forEach(key => {
            if (key === '$id') return;
            const newKey = key.charAt(0).toLowerCase() + key.slice(1);
            newContact[newKey] = contact[key];
          });
          return newContact;
        });
      }
      currentSupplier.value = formattedData;
    }
    detailDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取供应商详情失败');
    console.error('Failed to get supplier detail:', error);
  }
};

// 创建供应商
const handleCreate = () => {
  isEdit.value = false;
  // 重置表单
  Object.keys(supplierForm).forEach(key => {
    if (key === 'status') {
      supplierForm[key] = 1;
    } else if (key === 'supplierLevel') {
      supplierForm[key] = '普通供应商';
    } else if (key === 'invoiceType') {
      supplierForm[key] = '增值税专用发票';
    } else if (key === 'contactType') {
      supplierForm[key] = '业务';
    } else if (key === 'id') {
      supplierForm[key] = 0; // 新增时id设为0
    } else {
      supplierForm[key] = '';
    }
  });
  formDialogVisible.value = true;
};

// 编辑供应商
const handleEdit = async (supplier) => {
  try {
    const response = await apiRequest.get(`/api/Suppliers/${supplier.id}`);
    Object.assign(supplierForm, response.data);
    isEdit.value = true;
    formDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取供应商详情失败');
    console.error('Failed to get supplier detail for edit:', error);
  }
};

// 提交创建表单
const handleSubmit = async () => {
  try {
    // 准备提交数据，处理字段映射和格式问题
    // 准备提交数据，确保包含所有后端必填字段
    const submitData = {
      ...supplierForm,
      Phone: supplierForm.contactPhone?.replace(/"/g, '') || '', // 去除引号并映射到Phone字段
      SupplierCode: 'TEST' + Math.floor(Math.random() * 10000).toString().padStart(4, '0'), // 生成临时供应商编码
      // 映射后端必填字段
      // 邮箱字段已移除
      Address: supplierForm.address || 'Default Address',
      SupplierType: supplierForm.supplierType || 'DefaultType',
      SupplierLevel: supplierForm.supplierLevel || '普通供应商', // 确保提供供应商等级
      InvoicingPhone: supplierForm.invoicePhone || '13800138000',
      InvoicingAddress: supplierForm.invoiceAddress || 'Default Invoicing Address',
      BankNameAndAccount: supplierForm.bankAccount || 'Default Bank 123456',
      TaxIdentificationNumber: supplierForm.taxpayerId || '1234567890',
      InvoiceType: supplierForm.invoiceType || '增值税专用发票', // 确保提供发票类型
      // 联系人信息
      Contacts: [{
        ContactType: supplierForm.contactType,
        ContactName: supplierForm.contactPerson,
        Phone: supplierForm.contactPhone,
        Email: supplierForm.email,
        // 添加Supplier字段引用当前供应商
        Supplier: {
          id: supplierForm.id,
          supplierCode: 'TEST' + Math.floor(Math.random() * 10000).toString().padStart(4, '0'),
          supplierName: supplierForm.supplierName
        }
      }]
    };
    console.log('submitData:', submitData); // 输出提交数据
    const response = await createSupplier(submitData);
    ElMessage.success('创建供应商成功');
    formDialogVisible.value = false;
    loadSuppliers();
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '创建供应商失败');
    console.error('Failed to create supplier:', error);
    console.error('Error details:', error.response?.data); // 输出错误详情
  }
};

// 提交更新表单
const handleUpdate = async () => {
  try {
    const response = await updateSupplier(supplierForm.id, supplierForm);
    ElMessage.success('更新供应商成功');
    formDialogVisible.value = false;
    loadSuppliers();
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '更新供应商失败');
    console.error('Failed to update supplier:', error);
  }
};

// 变更状态
const handleStatusChange = async (supplier) => {
  try {
    const newStatus = supplier.status === 1 ? 0 : 1;
    await updateSupplierStatus(supplier.id, newStatus);
    ElMessage.success(`供应商已${newStatus === 1 ? '启用' : '禁用'}`);
    loadSuppliers();
  } catch (error) {
    ElMessage.error(`变更供应商状态失败`);
    console.error('Failed to change supplier status:', error);
  }
};

// 删除供应商
const handleDelete = (supplier) => {
  currentSupplier.value = supplier;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
    await deleteSupplier(currentSupplier.value.id);
    ElMessage.success('删除供应商成功');
    deleteDialogVisible.value = false;
    loadSuppliers();
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '删除供应商失败');
    console.error('Failed to delete supplier:', error);
  }
};

// 初始化
onMounted(() => {
  loadSuppliers();
});
</script>


<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>